import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild, OnInit } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap'; 
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { ProfileServiceProxy, OutsourcingWorkFlowViewDto, OutsourcingWorkFlowServiceProxy, ProcessingOrderServiceProxy, UserServiceProxy, ProcessingOrderStepUserDto, WorkflowServiceProxy, ProcessingOrderDto, ProcessingViewDto, ProcessingOrderInputDto, OutsouringServiceProxy } from '@shared/service-proxies/service-proxies';
import { from } from 'rxjs';

import { AccordionModule } from 'primeng/accordion';
import { SelectItem, SelectItemGroup } from 'primeng/api';

@Component({
  selector: 'OrderOutsourcedProcessingCreate',
  templateUrl: './OrderOutsourcedProcessingCreate.component.html',
  styleUrls: ['./OrderOutsourcedProcessingCreate.component.css']
})
export class OrderOutsourcedProcessingCreateComponent extends AppComponentBase implements OnInit { 
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('teskdataTable') teskdataTable: Table;
  // @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  active = false;
  saving = false;
  filterText = '';
  selectedCar3: string;
  detailsprimengTableHelper: PrimengTableHelper;
  _processingViewDto: ProcessingViewDto[];
  clonedOutsourcings: { [s: number]: ProcessingViewDto; } = {};
  _processingOrder: ProcessingOrderDto = new ProcessingOrderDto();
  workflow: OutsourcingWorkFlowViewDto;
  stepusers: ProcessingOrderStepUserDto;
  users: SelectItemGroup[];

  SupplierAyy: SelectItem[];

  selectProcessingViewDto: ProcessingViewDto[];
  index = 0;
  constructor(injector: Injector,
    private _outSourcingworkflowServiceProxy: OutsourcingWorkFlowServiceProxy,
    private _outSourcingServiceProxy: OutsouringServiceProxy,
    private _userService: UserServiceProxy,
    private _processingOrderServiceProxy: ProcessingOrderServiceProxy,
    private _workflowService: WorkflowServiceProxy
  ) {
    super(injector);
    this.detailsprimengTableHelper = new PrimengTableHelper();
    this.stepusers = new ProcessingOrderStepUserDto();
  }

  ngOnInit(): void {

    this.selectProcessingViewDto = new Array<ProcessingViewDto>();
    this._userService.getAllUserForDropDown().subscribe(resultdata => {
      console.log(resultdata);
      this.users = resultdata;
    });
  }

  show(): void {
    this.active = true;
    this.modal.show();
  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }
  onShown(): void {

  }
  getTasks(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }
    this.primengTableHelper.showLoadingIndicator();
    this._outSourcingworkflowServiceProxy.getOutsourcingFormModelByCode(
      0,
      this.filterText,
      'Code',
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event)
    )
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
      .subscribe(result => {
        console.log(result);
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
        _.forEach(result.items, viewItem => {
          if (viewItem.workflowId !== '') {
            console.log(viewItem.workflowId);
            this._workflowService.getWorkflowByWorkflowid(viewItem.workflowId)
              .subscribe(workflowtype => {
                viewItem.applyType = workflowtype;
              });
          } else {
            viewItem.applyType = '-';
          }
        });
      });
  }

  //依据申请单获取任务
  SelectTask(record) {
    console.log(record);
    let _supplier = record.supplierUnit.split(',');
    this.SupplierAyy =  new Array(); 
    _.forEach(_supplier, viewItem => {
      console.log(viewItem);
      this.SupplierAyy.push({ label: viewItem, value: viewItem });
    });
    this._processingOrder.supplierUnit = this.SupplierAyy[0].value;
 
    this.workflow = record;
    this._processingOrder.requisitionCode = record.code;
    this._outSourcingServiceProxy.getOutsourcingByWorkFlowId(record.workflowId).subscribe(dto => {
      console.log(dto);
      this._processingViewDto = dto;
      this.detailsprimengTableHelper.totalRecordsCount = dto.length;
      this.detailsprimengTableHelper.records = dto;
      this.detailsprimengTableHelper.hideLoadingIndicator();

      _.forEach(dto, viewItem => {
        console.log(viewItem.workflowId);
        this._processingOrderServiceProxy.getProcessingAmountForTaskId(viewItem.taskForModelId, record.code)
          .subscribe(amount => {
            viewItem.appliedAmount = amount;
          });
      });


    });

    this._outSourcingworkflowServiceProxy.buildProcessingOrderCodeByOutsourcingCode(record.code).subscribe(code => {
      this._processingOrder.orderCode = code;
    });
    this.index = 1;
    console.log(this.index);
  }

  handleChange(e) {
    this.index = e.index;
    console.log(this.index);
  }
 

  onRowEditInit(quotationmodel: ProcessingViewDto) {
    console.log(quotationmodel);
    quotationmodel.processingAmount = quotationmodel.outsouringAmount;
    this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
  }

  onRowEditSave(quotationmodel: ProcessingViewDto) {
    console.log(quotationmodel);
    if (quotationmodel.outsouringAmount > 0) {
      delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];

      var _current = this.selectProcessingViewDto.find((element) => (element.taskForModelId == quotationmodel.taskForModelId));
      if (_current == undefined) {
        quotationmodel.processingAmount = quotationmodel.outsouringAmount;
        this.selectProcessingViewDto.push(quotationmodel);
      }
      else {
        _current.materialsupply = quotationmodel.materialsupply;
        _current.unitprice = quotationmodel.unitprice;
        _current.explain = quotationmodel.explain;
      }

    } else {
      this.notify.info('申请数量不能小于0');
    }
  }

  onRowEditCancel(quotationmodel: ProcessingViewDto, index: number) {
    console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
    this._processingViewDto[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
    delete this._processingViewDto[quotationmodel.taskForModelId];
  }

  save() {
    let input = new ProcessingOrderInputDto();
    // tslint:disable-next-line: triple-equals
    if (this.workflow.applyType == '一般过程外协申请') {
      input.workFlowName = '一般过程外包加工申请';
      // tslint:disable-next-line: triple-equals
    } else if (this.workflow.applyType == '关键过程外协申请') {
      input.workFlowName = '关键过程外包加工申请';
    }
    console.log(this.selectProcessingViewDto);
    if (this.selectProcessingViewDto.length == 0) {
      this.notify.info('未选择加工单内容');
      this.saving = false;
      return;
    }

    //判断审批用户是否设置
    if (!this.stepusers.outsourcingPlanned) {
      this.notify.info('请选择外协计划员');
      this.saving = false;
      return;
    }
    if (!this.stepusers.modelManagerPlanned) {
      this.notify.info('请选择型号主管计划员');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionLeader) {
      this.notify.info('计划生产处主管处长');
      this.saving = false;
      return;
    }

    input.stepUserDto = this.stepusers;
    input.processingOrderDto = this._processingOrder;
    input.processingViewDtos = this.selectProcessingViewDto;
    this.saving = true;

    console.log(input);
    this._outSourcingworkflowServiceProxy.createOrUpdateProcessingWorkFlow(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.close();
      });
  }

}
